﻿CREATE PROCEDURE [ServiceEngine].[DeleteDataEntity]
@ID UNIQUEIDENTIFIER
AS
BEGIN
	DECLARE @ErrorMessage NVARCHAR(4000);
	DECLARE @ErrorSeverity INT;
	DECLARE @ErrorState INT;
	SET NOCOUNT ON;

	BEGIN TRY
		BEGIN TRANSACTION
		
		--Delete dependencies
		DELETE ServiceEngine.SchemaObjectDependencies
		FROM ServiceEngine.SchemaObjectDependencies JOIN
			ServiceEngine.SchemaObjects ON 
			ServiceEngine.SchemaObjectDependencies.ParentObjectID = ServiceEngine.SchemaObjects.SchemaObjectID
		WHERE
			ServiceEngine.SchemaObjects.DataEntityID = @ID

		DELETE ServiceEngine.SchemaObjects
		FROM ServiceEngine.SchemaObjects JOIN
			 ServiceEngine.DataEntities ON 
			ServiceEngine.DataEntities.DataEntityID = ServiceEngine.SchemaObjects.DataEntityID
		WHERE
			ServiceEngine.SchemaObjects.DataEntityID = @ID
			
		DELETE	ServiceEngine.DataEntities 
		WHERE	DataEntityID = @ID

		DELETE	ServiceEngine.Names
		WHERE	EntityID = @ID and EntityTypeID = 20
		
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();

		IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;

		RAISERROR (@ErrorMessage, 
				   @ErrorSeverity,
				   1);
	END CATCH
END

